package com.bootdo.app.controller;

import com.bootdo.app.htmlVO.goods.GoodsDetail;
import com.bootdo.app.htmlVO.order.OrderProductItemsDetails;
import com.bootdo.app.htmlVO.order.UserOrderDetail;
import com.bootdo.app.service.AppSellerService;
import com.bootdo.app.utils.AppUtilXML;
import com.bootdo.app.utils.returnresponse.ServerResponse;
import com.bootdo.appsystem.domain.*;
import com.bootdo.appsystem.service.*;
import com.bootdo.appsystem.vo.OrderProductAndUserInfo;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.utils.HttpContextUtils;
import com.bootdo.common.utils.HttpServletUtils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 【@author 】 @fan
 * 【@Email  】 mooncluyed@outlook.com
 * 【类解释  】
 * 【@Date   】 2018/5/12 0012
 **/
@Controller
@RequestMapping("/app/seller/")
public class AppSellerController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SellerService sellerService;
    @Autowired
    private AppSellerService appSellerService;
    @Autowired
    private ImageinfoService imageinfoService;
    @Autowired
    private ProducesinfoService producesinfoService;
    @Autowired
    private OrderproductService orderproductService;
    @Autowired
    private OrderproductitemsService orderproductitemsService;
    @Autowired
    private EvaluateService evaluateService;
    @Autowired
    private OrderaddressinfoService orderaddressinfoService;

    //    去商家认证页面
    @GetMapping("toseller")
    private String toSeller(){
        return "app/seller/seller";
    }
    //去商家上传主图页面
    @GetMapping("tosellermentouimage")
    private String tosellermentouimage(){
        return "app/seller/sellermentouimage";
    }

//    去商家上传图片页面
    @GetMapping("toappsellerimages")
    private String toApplySellerImages(){
        return "app/seller/applyimages";
    }

//    去商家认证页面
    @GetMapping("applysellerrenzheng")
    private String toApplySellerRenzheng(){
        return "app/seller/applysellerrenzheng";
    }

//    收款二维码
    @GetMapping("sellerCode")
    public String toMyqrCode(){
        return "app/seller/sellerQrCode";
    }

    //
    @GetMapping("toSellerGoods")
    public String toSellerGoods(){
        return "app/seller/goodsListSeller";
    }

    //      去商家订单列表
    @GetMapping("toSellerOrders")
    public String toSellerOrders() {
        return "app/seller/sellerOrder";
    }



    //商家订单数据
    @ResponseBody
    @PostMapping("msgSellerOrderList")
    public ServerResponse<PageUtils> msgOrderList(@RequestParam Map<String, Object> params){
        UseraccountDO sessionCustomer = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        params.put("sellerid" , sessionCustomer.getSellerid());
        Query query = new Query(params);
        List<OrderProductAndUserInfo> list = orderproductService.listAndUserInfo(query);
        int total = orderproductService.countAndUserInfo(query);

        PageUtils pageUtils = new PageUtils(list, total);
        return ServerResponse.createBySuccess(pageUtils);
    }


    // 去商家订单详情页
    @GetMapping("toUserOrderDetail")
    public String toUserOrderDetail(String orderCode , Model model){

        UseraccountDO useraccountDO = (UseraccountDO) HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("sellerid" , useraccountDO.getSellerid());
        map.put("ordercode" , orderCode);

        //商家订单数据
        List<OrderproductDO> list = orderproductService.list(map);
        OrderproductDO orderproductDO = list.get(0);

        ArrayList<OrderProductItemsDetails> orderProductItemsDetailsList = new ArrayList<OrderProductItemsDetails>();
        //商家订单详情
        List<OrderproductitemsDO> goodsProductList = orderproductitemsService.getGoodsProductList(orderproductDO.getOid());
        for (OrderproductitemsDO orderproductitems : goodsProductList) {
            //      创建一个新的订单对象存放数据
            OrderProductItemsDetails orderProductItemsDetails = new OrderProductItemsDetails();
            //      获取评价列表
            EvaluateDO evaluateByOrderProductitem = evaluateService.getEvaluateByOrderProductitem(orderproductitems, orderproductDO.getUid());
            //      获取订单商品详情
            ProducesinfoDO producesinfoDO = producesinfoService.get(orderproductitems.getPid());

            orderProductItemsDetails.setEvaluateDO(evaluateByOrderProductitem);
            orderProductItemsDetails.setOrderproductitemsDO(orderproductitems);
            orderProductItemsDetails.setProducesinfoDO(producesinfoDO);
            orderProductItemsDetailsList.add(orderProductItemsDetails);
        }

        //获取用户地址信息
        OrderaddressinfoDO address = orderaddressinfoService.getByOrderCode(orderCode);

        model.addAttribute("address",address);
        model.addAttribute("orderProductItemsDetailsList",orderProductItemsDetailsList);

        return "app/seller/orderDetail";
    }


    /**
     * 去修改商品页面
     * @param pid
     * @param model
     * @return
     */
    @GetMapping("toEditSellerGoods")
    public String toEditSellerGoods(Integer pid , Model model){
        UseraccountDO useraccountDO = (UseraccountDO) this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        SellerDO sellerByUserId = sellerService.getSellerByUserId(useraccountDO.getUid());
        if (sellerByUserId!=null) {
            ProducesinfoDO producesinfoDO = producesinfoService.get(pid);
            if(producesinfoDO.getSellerid() == sellerByUserId.getSellerid()){
                HashMap<String, Object> map = new HashMap<>();
                map.put("sort","display");
                map.put("sort","imageid");
                map.put("order","asc");
                map.put("allid",producesinfoDO.getPid());
                map.put("type",12009);
                List<ImageinfoDO> swlist = imageinfoService.list(map);
                map.put("type",12010);
                List<ImageinfoDO> mainlist = imageinfoService.list(map);
                GoodsDetail goodsDetail = new GoodsDetail();
                goodsDetail.setProducesinfoDO(producesinfoDO);
                goodsDetail.setSwlist(swlist);
                goodsDetail.setMainlist(mainlist);

                model.addAttribute("goodsDetail", goodsDetail);
                return "/app/seller/editMail";
            }
        }
        return "/app/error";
    }

    /**
    *【方法解释】 商家入驻功能
     * * 入驻时先填入商家的基本信息
    *【@date】    2018/5/14 0014  上午 10:17
    *【@author】  @fan
    */
    @ResponseBody
    @PostMapping("applyseller")
    public ServerResponse applySeller(SellerDO sellerInfo){
        UseraccountDO useraccountDO = (UseraccountDO)HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);
        try {
            //填入商家基本信息
            sellerInfo.setUid(useraccountDO.getUid());
            sellerInfo.setStatus(0);
            sellerInfo.setShowindex(0);
            sellerInfo.setIsrenzheng(0);
            sellerInfo.setSellerautid(1.0);
            sellerInfo.setAddtime(new Date());
            sellerInfo.setSelleroutnumber(0);
            sellerInfo.setSellerxishu(1.0);
            sellerInfo.setSellerorderxishu(1.0);

            //查询是否曾经是商家，审核不通过了
            SellerDO sellerDO = sellerService.getSellerByUserId(useraccountDO.getUid());
            if(sellerDO != null){
                sellerInfo.setSellerid(sellerDO.getSellerid());
                int i = sellerService.update(sellerInfo);
                if(i > 0) {
                    return ServerResponse.createBySuccess();
                }
            }else {
                int i = sellerService.save(sellerInfo);
                if(i > 0){
                    return ServerResponse.createBySuccess();
                }
            }
        }catch (RuntimeException e){
            return ServerResponse.createByErrorMessage("入驻失败，请先登录");
        }
        return ServerResponse.createByErrorCodeMessage(100,"入驻失败，请联系客服");
    }


    /**
    *【方法解释】上传商家图片接口
    *【参数】
    */
    @ResponseBody
    @PostMapping("msgapplysellerimages")
    public ServerResponse msgAddSellerImages(@RequestParam("file")MultipartFile file , HttpServletRequest request , Integer display){
        if(file == null){
            return ServerResponse.createByErrorMessage("未上传图片");
        }
        //获取用户的商家信息
        SellerDO sellerDO = appSellerService.getSessionSellerDO();
        //商家上传图片
        UseraccountDO useraccountDO = (UseraccountDO)request.getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        FileDO sysFile = appSellerService.uploadSellerImage(file,useraccountDO);

//      将上传文件的信息存放在数据库中。数据库为ImageInfo
        ImageinfoDO imageinfoDO = new ImageinfoDO();
        imageinfoDO.setType(2);
        imageinfoDO.setAllid(sellerDO.getSellerid());
        imageinfoDO.setDisplay(display);
        imageinfoDO.setImgurl(sysFile.getUrl());
//        图片状态设置为1 ， 此图片未被删除，正被审核中
        imageinfoDO.setImagetype(1);

        imageinfoService.save(imageinfoDO);

        return ServerResponse.createBySuccess(sysFile);
    }

    /**
     *【方法解释】上传商家图片接口
     *【参数】
     */
    @ResponseBody
    @PostMapping("msgaddsellerrenzhengimages")
    public ServerResponse msgAddSellerRenzhengImages(@RequestParam("file")MultipartFile file , HttpServletRequest request){
        if(file == null){
            return ServerResponse.createByErrorMessage("未上传图片");
        }
        //获取用户的商家信息
        SellerDO sellerDO = appSellerService.getSessionSellerDO();
        //商家上传图片
        UseraccountDO useraccountDO = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        FileDO sysFile = appSellerService.uploadSellerImage(file,useraccountDO);
        HashMap<String , Object> map = new HashMap<String , Object>();
        map.put("allid",sellerDO.getSellerid());
        map.put("type",3);
        List<ImageinfoDO> imageinfoDOList = imageinfoService.list(map);
        if(imageinfoDOList.size() < 1){
//      将上传文件的信息存放在数据库中。数据库为ImageInfo
            ImageinfoDO imageinfoDO = new ImageinfoDO();
//        3、代表商家认证图片
            imageinfoDO.setType(3);
            imageinfoDO.setAllid(sellerDO.getSellerid());
            imageinfoDO.setDisplay(1);
            imageinfoDO.setImgurl(sysFile.getUrl());
//        图片状态设置为1 ， 此图片未被删除，正被审核中
            imageinfoDO.setImagetype(1);
            imageinfoService.save(imageinfoDO);
        }else {
            ImageinfoDO imageinfoDO = imageinfoDOList.get(0);
            imageinfoDO.setImgurl(sysFile.getUrl());
            imageinfoService.update(imageinfoDO);
        }
        return ServerResponse.createBySuccess(sysFile);
    }


    /**
     * 商家认证
     * @param file 文件
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("addapplysellerrenzheng")
    public ServerResponse addapplysellerrenzheng(@RequestParam("file")MultipartFile file , HttpServletRequest request){
        if(file == null){
            return ServerResponse.createByErrorMessage("未上传图片");
        }
        //获取用户的商家信息
        UseraccountDO useraccountDO = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        //商家上传图片
        FileDO sysFile = appSellerService.uploadSellerImage(file,useraccountDO);
        SellerDO sessionSellerDO = appSellerService.getSessionSellerDO();
        sessionSellerDO.setSellerimage(sysFile.getUrl());
        sellerService.update(sessionSellerDO);
        return ServerResponse.createBySuccess(sysFile);
    }

    /**
     * 上传商家门头图片
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("addapplysellermentou")
    public ServerResponse msgApplySellerMentou(@RequestParam("file")MultipartFile file , HttpServletRequest request){
        if(file == null){
            return ServerResponse.createByErrorMessage("未上传图片");
        }
        UseraccountDO useraccountDO = (UseraccountDO)request.getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        FileDO sysFile = appSellerService.uploadSellerImage(file,useraccountDO);
        return ServerResponse.createBySuccess(sysFile);
    }

    /**
     * 上传商家详情图
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("msgapplysellerimagesLiko")
    public ServerResponse<FileDO> msgApplySellerImages(@RequestParam("file")MultipartFile file , HttpServletRequest request ,Integer imageIndex) {
        if(file == null){
            return ServerResponse.createByErrorMessage("未上传图片");
        }
        UseraccountDO useraccountDO = (UseraccountDO)request.getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        FileDO sysFile = appSellerService.uploadSellerImage(file,useraccountDO);
        ImageinfoDO imageinfoDO = new ImageinfoDO();
        imageinfoDO.setImgurl(sysFile.getUrl());
        imageinfoDO.setAllid(useraccountDO.getUid());
        imageinfoDO.setDisplay(imageIndex);
        imageinfoDO.setType(10006);
        imageinfoDO.setImagetype(0);
        imageinfoDO.setImgdesc("商家详情图");
        imageinfoService.save(imageinfoDO);
        return ServerResponse.createBySuccess(sysFile);
    }


    /**
     * 商家商品商品主列表
     * @param params 传入当前登录商家编号
     * @return
     */
    @ResponseBody
    @GetMapping("sellerGoods")
    public ServerResponse<PageUtils> msgGoodsList(@RequestParam Map<String, Object> params){
        if (params.get("categoryid").equals("0")) {
            params.remove("categoryid");
        }
        UseraccountDO useraccountDO = (UseraccountDO) this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        SellerDO sellerByUserId = sellerService.getSellerByUserId(useraccountDO.getUid());
        params.put("sellerid",sellerByUserId.getSellerid());
        Query query = new Query(params);
        List<ProducesinfoDO> producesinfoDOList = producesinfoService.list(query);
        int total = producesinfoService.count(query);
        PageUtils pageUtils = new PageUtils(producesinfoDOList, total);
        return ServerResponse.createBySuccess(pageUtils);
    }
















}
